package com.yc.cloud.basic.rsa;

import cn.hutool.core.io.FileUtil;

import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

public class RSAKeyPairGenerator {
    private PublicKey publicKey;
    private PrivateKey privateKey;

    public RSAKeyPairGenerator() throws NoSuchAlgorithmException {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);
        KeyPair pair = keyGen.generateKeyPair();
        this.publicKey = pair.getPublic();
        this.privateKey = pair.getPrivate();
    }

    public PublicKey getPublicKey() {
        return this.publicKey;
    }

    public PrivateKey getPrivateKey() {
        return this.privateKey;
    }

    public static void main(String[] args) {
        try {
            RSAKeyPairGenerator keyPairGenerator = new RSAKeyPairGenerator();
            // 将公钥保存到文件
            PublicKey publicKey = keyPairGenerator.getPublicKey();
            byte[] publicKeyBytes = publicKey.getEncoded();
            String publicKeyBase64 = Base64.getEncoder().encodeToString(publicKeyBytes);
            FileUtil.writeBytes(publicKeyBase64.getBytes(), "/Users/jackgu/Documents/workspace/java/yccloud_background/document/publicKey.pub");

            // 将私钥保存到文件
            PrivateKey privateKey = keyPairGenerator.getPrivateKey();
            byte[] privateKeyBytes = privateKey.getEncoded();
            String privateKeyBase64 = Base64.getEncoder().encodeToString(privateKeyBytes);
            //keyPairGenerator.writeToFile("privateKey.key", privateKeyBase64.getBytes());
            FileUtil.writeBytes(privateKeyBase64.getBytes(), "/Users/jackgu/Documents/workspace/java/yccloud_background/document/privateKey.key");
            System.out.println("公钥和私钥已被保存到文件");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

